package com.haruhi.botopq.utils;

import cn.hutool.system.SystemUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;

@Slf4j
public class FileUtils {

    public void writeStopScript(){

        String s = null;
        String scriptName = null;
        if(SystemUtils.IS_OS_LINUX || SystemUtils.IS_OS_MAC){
            s = MessageFormat.format("kill -9 {0}", SystemUtil.getCurrentPID());
            scriptName = "stop.sh";
        }else if (SystemUtils.IS_OS_WINDOWS){
            s = MessageFormat.format("taskkill /pid {0} -t -f",SystemUtil.getCurrentPID());
            scriptName = "stop.bat";
        }else {
            return;
        }
        if (StringUtils.isNotBlank(s)) {
            File file = new File(getAppDir() + File.separator + scriptName);
            writeText(file,s);
            log.info("生成停止脚本完成:{}",file);
        }
        
    }


    /**
     * 往文件中写入文本(覆盖原内容)
     * 不存在则创建文件
     * @param file
     * @param text
     */
    public static void writeText(File file,String text){
        if (file == null || text == null) {
            throw new NullPointerException("file or text is null");
        }
        FileOutputStream fos = null;
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            fos.write(text.getBytes(StandardCharsets.UTF_8));
        }catch (IOException e){
            log.error("写入文本异常",e);
        }finally {
            try {
                fos.flush();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            try {
                fos.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    public static void writeText(String file,String text){
        writeText(new File(file),text);
    }

    public static String getAppDir() {
        try {
            return new ClassPathResource("").getFile().getAbsolutePath();
        } catch (IOException e) {
            return FileUtils.class.getClassLoader().getResource("").getPath();
        }
    }

    public static void main(String[] args) {
        System.out.println(SystemUtil.getCurrentPID());
        System.out.println(getAppDir());
    }
}
